package com.example.sensordemo;

import com.example.sensordemo.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.hiviewdfx.HiLog;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

import java.util.List;
import java.util.function.Consumer;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        requestPermission();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == 0) {
                // 权限被授予
                // 输出所支持的运动类传感器
                CategoryOrientationAgent agent = new CategoryOrientationAgent();
                List<CategoryOrientation> sensorList = agent.getAllSensors();
                sensorList.forEach(new Consumer<CategoryOrientation>() {
                    @Override
                    public void accept(CategoryOrientation categoryOrientation) {
                        HiLog.info(null, "支持的传感器" + categoryOrientation.getName());
                    }
                });

                agent.setSensorDataCallback(new ICategoryOrientationDataCallback() {
                    @Override
                    public void onSensorDataModified(CategoryOrientationData categoryOrientationData) {}

                    @Override
                    public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int i) {}

                    @Override
                    public void onCommandCompleted(CategoryOrientation categoryOrientation) {}
                }, agent.getSingleSensor(CategoryOrientation.SENSOR_TYPE_ORIENTATION), (long)1);

            } else {
                // 权限被拒绝
            }
        }
    }

    void requestPermission() {
        if (verifySelfPermission("ohos.permission.ACTIVITY_MOTION") != 0) {
            if (canRequestPermission("ohos.permission.ACTIVITY_MOTION")) {
                requestPermissionsFromUser(new String[] {"ohos.permission.ACTIVITY_MOTION"}, 1);
            }
        }
    }
}
